﻿//-----------------------------------------------------------------------------------
// LoadTest Plugin Template version 1.0
//-----------------------------------------------------------------------------------
using System;
using Microsoft.VisualStudio.TestTools.LoadTesting;
using System;
using System.Collections;
using Microsoft.VisualStudio.TestTools.LoadTesting;


namespace WebLoadDemo
{
    public class LoadChangerPlugin : ILoadTestPlugin
    {
        public void Initialize(LoadTest loadTest)
        {
            m_loadTest = loadTest;
            loadTest.Heartbeat += new EventHandler<HeartbeatEventArgs>(loadTest_Heartbeat);
        }

        void loadTest_Heartbeat(object sender, HeartbeatEventArgs e)
        {
            if (!switched && e.ElapsedSeconds >= m_secondsUntilSwitch)
            {
                DecreasingLoadProfile profile = new DecreasingLoadProfile();
                profile.MaxUserCount = MaxUserCount;
                profile.MinUserCount = MinUserCount;
                m_loadTest.Scenarios[0].LoadProfile = profile;
                switched = true;
            }
        }

        public int MinUserCount
        {
            get
            {
                return m_minUserCount;
            }
            set
            {
                m_minUserCount = value;
            }
        }

        public int MaxUserCount
        {
            get
            {
                return m_maxUserCount;
            }
            set
            {
                m_maxUserCount = value;
            }
        }

        public int SecondsUntilSwitch
        {
            get
            {
                return m_secondsUntilSwitch;
            }
            set
            {
                m_secondsUntilSwitch = value;
            }
        }

        private int m_minUserCount;
        private int m_maxUserCount;
        private int m_secondsUntilSwitch;
        private bool switched;

        private LoadTest m_loadTest;
    }

    [Serializable]
    public class DecreasingLoadProfile : LoadTestLoadProfile
    {
        public override int GetLoad(int elapsedSeconds)
        {
            int userLoad = Math.Max(MaxUserCount - elapsedSeconds, MinUserCount);

            return userLoad;
        }

        public override void Validate()
        {
            if (MinUserCount > MaxUserCount)
            {
                throw new InvalidLoadProfileException("MinUserCount is greater than MaxUserCount");
            }
        }
    }
}

